
package cfar.actors.distributed;

import cfar.actors.Message;
import cfar.actors.RemoteActor;

import cfar.ff.data.Assocs.Assoc2;
import cfar.ff.data.Maybe;
import cfar.ff.fun.F0;

import static cfar.ff.data.Maybe.*;
import static cfar.utils.IO.*;

import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;

/**
 *
 * @author badi
 */
public class CRCActor extends RemoteActor {

    protected final String sync_dir;
    protected final Maybe<String> address;
    protected final Maybe<String> sync_file;

    public CRCActor(final String sync_dir, final String suffix) throws IOException{
        super();
        this.sync_dir = sync_dir;

        if(my_address.isJust && my_port.isJust){
            final InetAddress a = my_address.from();
            address = just(a.getHostName() + "-" + my_port.from());
            sync_file = just(sync_dir + File.separator + address + "." + suffix);

            Integer port = my_port.from();
            Assoc2<InetAddress, Integer> location = new Assoc2<InetAddress, Integer>(a, port);

            write_object(location, new FileOutputStream(sync_file.from()));
        }else {
            address = nothing();
            sync_file= nothing();
        }
    }

    @Override
    protected void cleanup(){
        new File(sync_file.from()).delete();
    }

    @Override
    protected void act(Message msg, Socket client) {
        if(msg.signal instanceof Signal.WorkF0){
            F0 f = (F0) msg.payload;
            Object r =  f.call();
            Assoc2<Maybe<String>, Object> res = new Assoc2<Maybe<String>, Object>(address, r);
            try {
                write_object(new Message(Signal.Result, res), client.getOutputStream());
            } catch (IOException ex) {
                Logger.getLogger(CRCActor.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else { unknown_signal(msg); }
    }

}
